/**
 * @author helio
 */
var comboxTpl = new Ext.XTemplate(
	'<tpl for="."><div class="x-combo-list-item">{name}</div></tpl>'
);

var comboxTplCode = new Ext.XTemplate(
	'<tpl for="."><div class="x-combo-list-item">{code}</div></tpl>'
);

var comboxTplLoginid = new Ext.XTemplate(
	'<tpl for="."><div class="x-combo-list-item">{loginid}</div></tpl>'
);

var productTpl = new Ext.XTemplate(
	'<tpl for="."><div class="x-combo-list-item">{name}<div><font color="red">{specs}</font></div><div><font color="red">{model}</font></div></div></tpl>'
);

var saleItemTemplate = new Ext.XTemplate(
	'<tpl for=".">',
		'<div class="item-info" id="{pname}">',
		'<b>商品名称:</b>',
		'<span>{pname}</span>',
		'<b>单价:</b>',
		'<span>{pprice}</span>',
		'<b>数量:</b>',
		'<span>{pnumber}</span>',
		'<b>金额:</b>',
		'<span>{pamount}</span></div>',
	'</tpl>'	
);

var BasicPanel = function(args) {
	this.inputForm;
	this.formDataJson = !args ? null : args.formData;
	this.detailsGrid;
	this.detailsJson = (args && args.details) ? args.details : {details:[]};
	this.detailsStore;
	this.task = !args ? null : args.task;
	this.selectedRowIndex;
	this.selectedRecordList;
}

BasicPanel.prototype = {
	synchronizeJson: function(){
		
		if(!this.formDataJson) {
			this.formDataJson = {};
		} 
		
		for (var i = 0; i < this.inputForm.form.items.length; i++) {
			var fieldName = this.inputForm.form.items.itemAt(i)["name"];
			if(this.inputForm.form.findField(fieldName)) {
				this.formDataJson[fieldName] = this.inputForm.form.findField(fieldName).getValue();
			}
		}
	},
	
	synchronizeForm: function(){
		for(var attri in this.formDataJson) {
			
			if(this.inputForm.form.findField(attri) != null && this.formDataJson[attri]) {
				if(attri.indexOf("date") > 0 && this.formDataJson[attri]) {
					this.inputForm.form.findField(attri).setValue(new Date(this.formDataJson[attri]));
				} else {
					this.inputForm.form.findField(attri).setValue(this.formDataJson[attri]);
				}				
			}
		}
	},
	
	setRadioGroupValue : function(id, value) {
//		var radiogroup = Ext.getCmp(id);
//		if(radiogroup) {
//			radiogroup.items.each(function(f){
//	　　　　　　　 	if(value == f.inputValue){　　
//	　　　　　　　 		f.setValue(true);　　
//	　　　　　　　 	}else{　　
//	　　　　　　　　　　　 	f.setValue(false);　　
//	　　　　　　　 	}　　
//	　　		});
//		}		
		var radiogroup = Ext.query("*[name=" + id + "]");
		if(radiogroup) {
			Ext.each(radiogroup,function(f){
	　　　　　　　 	if(value == f.value){　　
	　　　　　　　 		f.checked = true;　　
	　　　　　　　 	}else{　　
	　　　　　　　　　　　 	f.checked = false;　
	　　　　　　　 	}　　
	　　		});
		}
	},
	
	setCode: function(code) {
		var codeField = this.inputForm.form.findField("code");
		if(codeField) {
			codeField.setValue(code);
		}
	},
	
	clearForm : function() {
		this.inputForm.form.reset();
	},
	
	clearJson : function() {
		this.synchronizeJson();
	},
	
	clearGrid : function() {
		if (this.detailsJson) {
			var details = this.detailsJson.details;
			for (var i = 0; i < details.length; i++) {
				var detail = details[i];
				for (var attri in detail) {
					detail[attri] = "";
				}
			}
			this.detailsStore.reload();
		}
	},
	
	clear : function() {
		this.clearForm();
		this.clearJson();
	},
	
	showMessage: function(message, title){
		SALE.Utils.showMessageBox(message, title);
	},
	
	warnMessage: function(message, title){
		Ext.MessageBox.show({
           	title: !title ? '警告信息' : title,
           	msg: message,
          	buttons: Ext.MessageBox.OK,
           	icon: Ext.MessageBox.WARNING
       	});
	},
	
	confirmMessage: function(message, title, fn){
		Ext.MessageBox.show({
           	title: !title ? '警告信息' : title,
           	msg: message,
          	buttons: Ext.MessageBox.OKCANCEL,
			fn: fn,
           	icon: Ext.MessageBox.QUESTION
       	});
	},
	
	showModifyDataHandler : function(resultJson) {
		this.formDataJson = resultJson;
		this.task = "modify";
		this.showEditeWin();
	},
	
	saveSuccessHandler : function(result) {		
		if(!result || result.success) {
			this.refreshGridRecord(result ? result.record : null);
			if (this.inputWin) this.inputWin.hide();
			
			if (result && result.message) {
				this.showMessage(result.message);
			} else {
				this.showMessage("添加/修改成功！！！");
			}
		} else if(this.inputWin) {			
			this.showMessage(result.message);
		}		
	},
	
	saveBillSuccessHandler : function() {
		this.showMessage("添加/修改成功！！！");
		this.clear();		
		this.clearGrid();
	},
	
	deleteSuccessHandler : function() {
		
		for (var i = 0; i < this.selectedRecordList.length; i++) {
			this.detailsGrid.getStore().remove(this.selectedRecordList[i]);
		}
		
		this.showMessage("删除成功！！！");
	},
	
	refreshGridByStore : function(newStore) {
		newStore.load();

		this.detailsStore.removeAll();
		var records = newStore.getRange(0, newStore.getTotalCount());
		this.detailsStore.add(records);
	},
	
	refreshGridByArray : function(results) {

		this.detailsJson.details = results;
		this.detailsStore.reload();
		SALE.Utils.hideLoadMask();
	},
	
	refreshGridRecord : function(recordJson) {		
		if(!recordJson) {
			recordJson = this.formDataJson;
		}
		
		if(this.task === 'new') {
			var temp = [];
			for(var key in recordJson){
			   var keyObj = {'name': key};
			   temp.push(keyObj);
			}			
			var NewRecord = new Ext.data.Record.create(temp);
			
			var record = new NewRecord(recordJson);
			this.detailsGrid.getStore().addSorted(record);
		} else if(recordJson) {
			var record = this.detailsGrid.getStore().getAt(this.selectedRowIndex);
			if(record) {
				for(var i = 0; i < record.fields.length; i++) {
					var recordName = record.fields.itemAt(i)["name"];
					record.set(recordName, recordJson[recordName]);
				}
				record.commit();
			}			
		}
		
	},
	
	showLineChartHandler : function(initData) {
		var data = initData.data;
		var title = !initData.title ? "统计分析图" : initData.title;
		var chart = SALE.view.chartView.createLineChartPanel(data, title);
			
		if(chart){
			SALE.App.showNextOperateTabPanel(chart, "统计分析图");
		}						
	},
	
	showColumnChartHandler : function(initData) {
		var data = initData.data;
		var title = !initData.title ? "统计分析图" : initData.title;
		var chart = SALE.view.chartView.createColumnChartPanel(data, title);
			
		if(chart){
			SALE.App.showNextOperateTabPanel(chart, "统计分析图");
		}						
	}
}

if(!SALE.basicGridPanel) SALE.basicGridPanel = Ext.extend(Ext.Panel, {
	clear : function() {
		if (this.detailsJson) {
			var details = this.detailsJson.details;
			for (var i = 0; i < details.length; i++) {
				var detail = details[i];
				for (var attri in detail) {
					detail[attri] = "";
				}
			}
			this.detailsStore.reload();
		}
	},
	
	close : function() {
		this.findParentByType("window").close();
	},
	
	hide : function() {
		this.findParentByType("window").hide();
	},
	
	showMessage: function(message, title){
		SALE.Utils.showMessageBox(message, title);
	},
	
	errorMessage: function(message, title){
		Ext.MessageBox.show({
           	title: !title ? '错误信息' : title,
           	msg: message,
          	buttons: Ext.MessageBox.OK,
           	icon: Ext.MessageBox.ERROR
       	});
	},
	
	saveSuccessHandler : function(result) {		
		if(!result || result.success) {			
			if (this.inputWin) this.inputWin.hide();
			
			if (result && result.message) {
				this.showMessage(result.message);
			} else {
				this.showMessage("添加/修改成功！！！");
			}
			
			this.clear();
		} else if(!result.success) {			
			this.showMessage(result.message);
		}		
	},
	
	insertOneRowHandler : function() {
		var Row = this.detailsGrid.getStore().recordType;
		var store = this.detailsGrid.getStore();
        var r = new Row({});
        this.detailsGrid.stopEditing();
        store.insert(store.getCount(), r);
        this.detailsGrid.startEditing(store.getCount() - 1, 1);
	},
		
	deleteRowsHandler : function() {
		this.selectedRecordList = this.detailsGrid.getSelectionModel().getSelections();
		if(this.selectedRecordList.length == 0) {
			this.showMessage('请选择你要删除的行！！！', '警告');
		} else {
			Ext.MessageBox.confirm('删除确认', '你真的要删除选中的行吗?', function(btn) {
				if (btn == "yes") {
					for(var i = 0; i < this.selectedRecordList.length ; i++) {
						this.detailsGrid.getStore().remove(this.selectedRecordList[i]);
					}
					this.detailsGrid.getView().refresh();
				}
			}.createDelegate(this));				
		}
			
	}
});

if(!SALE.basicWindow) SALE.basicWindow = Ext.extend(Ext.Window, {
	showWindow : function(successCallback, initJson, task) {
		this.successCallback = successCallback;
		this.formJson = initJson;
		this.task = task;
		this.show();
	},
	
	clear : function() {
		this.inputForm.form.reset();
		this.formJson = {};
	},
	
	syncJson: function(){
		
		if(!this.formJson) {
			this.formJson = {};
		} 
		
		for (var i = 0; i < this.inputForm.form.items.length; i++) {
			var fieldName = this.inputForm.form.items.itemAt(i)["name"];
			if(this.inputForm.form.findField(fieldName)) {
				this.formJson[fieldName] = this.inputForm.form.findField(fieldName).getValue();
			}
		}
	},
	
	syncForm: function(){
		for(var attri in this.formJson) {
			
			if(this.inputForm.form.findField(attri) != null && this.formJson[attri]) {
				if(attri.indexOf("date") > 0 && this.formJson[attri]) {
					this.inputForm.form.findField(attri).setValue(new Date(this.formJson[attri]));
				} else {
					this.inputForm.form.findField(attri).setValue(this.formJson[attri]);
				}				
			}
		}
	},
	
	showMessage: function(message, title){
		SALE.Utils.showMessageBox(message, title);
	},
	
	errorMessage: function(message, title){
		Ext.MessageBox.show({
           	title: !title ? '错误信息' : title,
           	msg: message,
          	buttons: Ext.MessageBox.OK,
           	icon: Ext.MessageBox.ERROR
       	});
	},
	
	saveSuccessHandler : function(result) {
		if(!result || result.success) {
			if (result && result.message) {
				this.showMessage(result.message);
			} else {
				this.showMessage("添加/修改成功！！！");
			}
			
			if (this.successCallback) this.successCallback(this.formJson);
			
			this.hide();
		} else if(!result.success) {			
			this.showMessage(result.message);
		}		
	},
	
	fileUploadHandler : function() {
		SALE.view.showUploadFileWin(function(url){
			this.inputForm.getForm().findField("imageurl").setValue(url);
			Ext.DomHelper.overwrite('imageview', {
	    		tag: 'img', src: url, 
	    		style:'margin:0 auto;visibility:hidden;',
	    		width: 150, height: 100
	    	}, true).show(true).frame();
		}.createDelegate(this));	
	},
	
	listeners: {
		'show': function() {
			this.syncForm();
		},
		
		'hide': function() {							
			this.clear();
		}
	}
});

//Add the additional 'advanced' VTypes
Ext.apply(Ext.form.VTypes, {
    daterange : function(val, field) {
        var date = field.parseDate(val);

        if(!date){
            return;
        }
        if (field.startDateField && (!this.dateRangeMax || (date.getTime() != this.dateRangeMax.getTime()))) {
            var start = Ext.getCmp(field.startDateField);
            start.setMaxValue(date);
            start.validate();
            this.dateRangeMax = date;
        } 
        else if (field.endDateField && (!this.dateRangeMin || (date.getTime() != this.dateRangeMin.getTime()))) {
            var end = Ext.getCmp(field.endDateField);
            end.setMinValue(date);
            end.validate();
            this.dateRangeMin = date;
        }
        /*
         * Always return true since we're only using this vtype to set the
         * min/max allowed values (these are tested for after the vtype test)
         */
        return true;
    },

    password : function(val, field) {
        if (field.initialPassField) {
            var pwd = Ext.getCmp(field.initialPassField);
            return (val == pwd.getValue());
        }
        return true;
    },

    passwordText : '两次输入的密码不一致。'
});

//创建换肤Panel
new Ext.ToolTip({ 
    id: 'theme-change-tip',
    target: 'changetheme',
    anchor: 'top',
    width: 100,
    autoHide: true,
    closable: true,
    items: new Ext.ColorPalette({
    	colors: ["99BBE8","9FD5C2","9F82FF","FF6363","875546","D0D0D0","C0C0C0","686868","485569","3D3D62","16181A"],//皮肤颜色的定义。
        listeners: {
	        select: function(cp, color){
    			SALE.Utils.changeTheme(color);//调用换肤的方法
	        }
	    }
	})    
});